package com.apikey.auth.controller;

import com.apikey.auth.entity.ApiKey;
import com.apikey.auth.service.ApiKeyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * API Key管理控制器
 * 提供API Key的CRUD操作接口
 *
 * @author API Key Framework
 * @version 1.0
 */
@RestController
@RequestMapping("/api/apikeys")
public class ApiKeyController {

    @Autowired
    private ApiKeyService apiKeyService;

    /**
     * 分页查询API Key列表
     *
     * @param page       页码，从0开始
     * @param size       每页大小
     * @param sort       排序字段
     * @param direction  排序方向
     * @param userId     用户ID过滤
     * @param status     状态过滤
     * @param permission 权限过滤
     * @return 分页结果
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getApiKeys(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "createdAt") String sort,
            @RequestParam(defaultValue = "desc") String direction,
            @RequestParam(required = false) String userId,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String permission) {

        try {
            Sort.Direction sortDirection = "desc".equalsIgnoreCase(direction) ?
                    Sort.Direction.DESC : Sort.Direction.ASC;
            Pageable pageable = PageRequest.of(page, size, Sort.by(sortDirection, sort));

            Page<ApiKey> apiKeys = apiKeyService.findApiKeys(userId, status, permission, pageable);

            Map<String, Object> response = new HashMap<>();
            response.put("content", apiKeys.getContent());
            response.put("totalElements", apiKeys.getTotalElements());
            response.put("totalPages", apiKeys.getTotalPages());
            response.put("currentPage", apiKeys.getNumber());
            response.put("size", apiKeys.getSize());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "获取API Key列表失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 根据ID获取API Key详情
     *
     * @param id API Key ID
     * @return API Key详情
     */
    @GetMapping("/{id:[0-9]+}")
    public ResponseEntity<ApiKey> getApiKey(@PathVariable Long id) {
        Optional<ApiKey> apiKey = apiKeyService.findById(id);
        return apiKey.map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 创建新的API Key
     *
     * @param apiKey API Key信息
     * @return 创建的API Key
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createApiKey(@RequestBody ApiKey apiKey) {
        try {
            ApiKey created = apiKeyService.createApiKey(apiKey);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", created);
            response.put("message", "API Key创建成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "创建API Key失败: " + e.getMessage());
            return ResponseEntity.status(400).body(errorResponse);
        }
    }

    /**
     * 更新API Key信息
     *
     * @param id     API Key ID
     * @param apiKey 更新的API Key信息
     * @return 更新后的API Key
     */
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateApiKey(@PathVariable Long id, @RequestBody ApiKey apiKey) {
        try {
            apiKey.setId(id);
            ApiKey updated = apiKeyService.updateApiKey(apiKey);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", updated);
            response.put("message", "API Key更新成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "更新API Key失败: " + e.getMessage());
            return ResponseEntity.status(400).body(errorResponse);
        }
    }

    /**
     * 切换API Key状态
     *
     * @param id API Key ID
     * @return 更新后的API Key
     */
    @PatchMapping("/{id}/toggle-status")
    public ResponseEntity<ApiKey> toggleStatus(@PathVariable Long id) {
        try {
            ApiKey updated = apiKeyService.toggleStatus(id);
            return ResponseEntity.ok(updated);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 续期API Key
     *
     * @param id   API Key ID
     * @param days 续期天数
     * @return 更新后的API Key
     */
    @PatchMapping("/{id}/renew")
    public ResponseEntity<ApiKey> renewApiKey(@PathVariable Long id, @RequestParam int days) {
        try {
            ApiKey renewed = apiKeyService.renewApiKey(id, days);
            return ResponseEntity.ok(renewed);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 删除API Key（软删除）
     *
     * @param id API Key ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteApiKey(@PathVariable Long id) {
        try {
            apiKeyService.deleteApiKey(id);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 获取API Key统计信息
     *
     * @return 统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getStats() {
        try {
            Map<String, Object> stats = new HashMap<>();
            stats.put("totalCount", apiKeyService.getTotalCount());
            stats.put("activeCount", apiKeyService.getActiveCount());
            stats.put("expiredCount", apiKeyService.getExpiredCount());
            stats.put("disabledCount", apiKeyService.getDisabledCount());

            // 添加前端期望的字段
            stats.put("expiringCount", apiKeyService.findExpiringApiKeys(7).size()); // 7天内即将过期
            stats.put("totalAccess", 0); // 默认值，可以从访问日志服务获取

            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "获取API Key统计失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }
}